﻿import sys;
import time
import json

import XOai
import games.XO.Rules.XOrules as XOrules
import games.XO.Rules.XOGameManager as XOGameManager
import bgtp.bgtp as bgtp
from platform.utilits import *

def name():
	return "AI"

def send(type, msg = ""):
	try:
		liba.send(name()+ ";" + type + ";" + json.dumps(msg))
	except:
		print "can't send to server"

def tryTurn():
	if (len(rules.data.fld) > 0 and rules.data.who == who):
		(best, bestTurn) = XOai.makeBestTurn(rules.data.fld, XOrules.getLfield(rules.data.fld), 0, who, who);
		msg = {};
		msg["X"] = bestTurn[0];
		msg["Y"] = bestTurn[1];		
		send("makeTurn", msg);

def receve():
	global do
	if len(stream) == 0:
		return
	
	msg = stream.pop()
	req = Request(msg)
	
	if req.type == "bye" or req.type == "stopGame":
		do = False
	elif req.type == "msg":
		if req.usr == USR_SERVER:
			if len(req.body) >= 0 and req.body.get("MSG_TYPE") == "startGame":
				send("getSituation")
		elif req.usr == USR_GAMEMANAGER:
			if len(req.body) >= 3:
				rules.doRequest(Request(req.body))
				tryTurn()
	elif req.type == "return_getSituation" and req.body.get(ANS_VAL) != False:
		rules.setSituation(req.body.get(ANS_VAL))
		tryTurn()

if sys.platform.count("java") == 0:
	sys.setcheckinterval(1) 
liba = bgtp.liba
liba.startClient()

stream = []
out = open("ai_log.txt", 'w')
liba.subscribe({}, out)
liba.subscribe({}, "stdout")
liba.subscribe({}, stream)

rules = XOGameManager.XOGameManager(lambda x: 0)
rules.client = True

who = XOrules.Ochar
send("hi"); 		time.sleep(0.3)
send("addGamer"); 	time.sleep(0.3)
send("setGamerParty", {"PARTY": who}); 	time.sleep(0.3)
send("getSituation");

do = True
while do:
	receve()
	time.sleep(0.01)
out.close()